import requests
import cv2
import json
import numpy as np
import base64
from io import BytesIO
def tran_points_index(potlist):
    tranIdx=[16,15, 14, 13, 12, 11, 10,  9 , 8 , 7 , 6,  5 , 4  ,3 , 2 , 1,  0, 56 ,57 ,58, 59, 60, 65, 64,
 63 ,62 ,61 ,17, 18 ,19, 20 ,21 ,22 ,23, 24, 25 ,47 ,46, 45 ,44 ,49, 48, 50 ,51, 52, 53 ,54 ,55,
 32 ,31, 30, 29, 28 ,27, 26 ,37 ,36 ,35 ,34 ,33, 66, 41, 42, 43, 67, 38 ,39, 40]
    newlist=[]
    for i in tranIdx:
        newlist.append(potlist[i])
    return newlist
def get_points68(img):
    #接口文档http://47.115.89.81:8086/docs#/

    # url = "http://47.115.89.81:8086/get_landmarks_b64_68/"
    url = "http://localhost:8086/get_landmarks_b64_68/"
    # url = "http://47.115.89.81:8086/get_landmarks_b64/"
    # 定义请求头
    headers = {
        "accept": "application/json",
    }
    result=None
    # 构造 multipart/form-data 请求
    try:
        _, buffer = cv2.imencode('.jpg', img)  # 假设我们将其编码为JPEG格式
        byte_arr = np.array(buffer)

        # 或者，可以直接使用BytesIO进行内存操作
        # byte_io = io.BytesIO()
        # cv2.imencode('.jpg', image)[1].tofile(byte_io)
        # byte_arr = byte_io.getvalue()

        # Step 3: 将字节流编码为base64字符串
        encoded_img = base64.b64encode(buffer)
        # 返回base64编码的字符串
        base64_str= encoded_img.decode('utf-8')  # 为了方便处理，通常会解码回文本格式
        data = json.dumps({
            "image": base64_str
        })

        response = requests.post(
            url, data=data, headers=headers
        )

        # 检查响应状态码
        if response.status_code == 200:
            print("请求成功！")
            result=response.json()
            # print("响应内容（JSON）:", response.json())
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print("错误信息:", response.text)

    except requests.exceptions.RequestException as e:
        print(f"请求异常: {e}")
    return result

if __name__=="__main__":
    image="./data/1005/whiteFace_face.jpg"
    img=cv2.imread(image)
    orig_h, orig_w = img.shape[:2]
    img_resize=cv2.resize(img,(orig_w//10, orig_h//10))
    result=get_points68(img_resize)
    print(result["box"])
    x1=result["box"]["x1"]
    x2=result["box"]["x2"]
    y1 = result["box"]["y1"]
    y2 = result["box"]["y2"]
    idx = 0
    cv2.rectangle(img_resize, (x1,y1), (x2,y2), (0,0,255), 1)
    cv2.imshow("copy_img", img_resize)

    cv2.waitKey()